<template>
  <a-card :bordered="false">
    <div class="table-page-search-wrapper">
      <a-form layout="inline">
        <a-row :gutter="20">
          <a-col v-show="showDepName" :md="6" :sm="24">
            <a-form-item label="部门名称">
              <a-select v-model="queryParam.depId" placeholder="请选择">
                <!--<a-select-option v-for="dep in depList" :key="dep.codeDetail" :value="dep.codeDetail">{{ dep.codeContent1 }}</a-select-option>-->
                <a-select-option v-for="dep in depList" :key="dep.itemVal" :value="dep.itemVal">{{ dep.itemDesc }}</a-select-option>
              </a-select>
            </a-form-item>
          </a-col>
          <a-col :md="6" :sm="24">
            <a-form-item label="合同名称">
              <a-input v-model="queryParam.contractName" placeholder="合同名称"/>
            </a-form-item>
          </a-col>
          <a-col :md="6" :sm="24">
            <a-form-item label="合同类別">
              <a-select v-model="queryParam.contractType" placeholder="请选择">
                <a-select-option v-for="type in contractTypeList" :key="type.itemVal" :value="type.itemVal">
                  {{ type.itemDesc }}</a-select-option>
              </a-select>
            </a-form-item>
          </a-col>
          <a-col :md="6" :sm="24">
            <a-form-item label="合同性质">
              <a-select v-model="queryParam.contractNature" placeholder="请选择">
                <a-select-option v-for="nature in contractNatureList" :key="nature.itemVal" :value="nature.itemVal">
                  {{ nature.itemDesc }}</a-select-option>
              </a-select>
            </a-form-item>
          </a-col>
          <a-col :md="6" :sm="24">
            <a-form-item label=" 总 金 额">
              <!-- <a-input type="number" oninput="value=value.replace(/[^\d]/g,'')" v-model="queryParam.totalAmount" placeholder="大于此金额"/> -->
              <a-input-group compact>
                <a-input v-model="queryParam.totalAmountMin" style="width: 40%; text-align: center" oninput="value=value.replace(/[^\d]/g,'')" placeholder="最小" />
                <a-input
                  style=" width: 20%; border-left: 0; pointer-events: none; backgroundColor: #fff"
                  placeholder="~"
                  disabled
                />
                <a-input v-model="queryParam.totalAmountMax" style="width: 40%; text-align: center; border-left: 0" oninput="value=value.replace(/[^\d]/g,'')" placeholder="最大" />
              </a-input-group>
            </a-form-item>
          </a-col>
          <!-- <template v-if="advanced"> -->
          <a-col :md="6" :sm="24">
            <a-form-item label="签 约  方">
              <a-input v-model="queryParam.partA" placeholder="签约方"/>
            </a-form-item>
          </a-col>
          <a-col :md="6" :sm="24">
            <a-form-item label="签约时间">
              <!-- <a-date-picker v-model="queryParam.signTimeTemp" valueFormat="YYYYMMDD" style="width: 100%" placeholder="签约时间"/> -->
              <a-range-picker v-model="queryParam.signTimeTemp" valueFormat="YYYYMMDD" style="width: 100%"/>
            </a-form-item>
          </a-col>
          <a-col :md="6" :sm="24">
            <a-form-item label="签约地点">
              <a-input v-model="queryParam.signAddr" placeholder="签约地点"/>
            </a-form-item>
          </a-col>
          <a-col :md="6" :sm="24">
            <a-form-item label="有 效 期">
              <a-range-picker v-model="queryParam.rangeTime" valueFormat="YYYYMMDD" style="width: 100%"/>
            </a-form-item>
          </a-col>
          <a-col :md="showDepName ? 18 : 24" :sm="24">
            <span class="table-page-search-submitButtons" :style="{ float: 'right', overflow: 'hidden' }">
              <a-button style="margin-left: 8px" v-action:import :loading="importLoading" @click="excelImport()">导入</a-button>
              <input
                ref="importInput"
                type="file"
                id="importFile"
                accept=".xls,.xlsx"
                @change="importFile()"
                hidden />
              <a-button style="margin-left: 8px" v-action:export @click="excelExport()">导出</a-button>
              <a-button style="margin-left: 8px" type="primary" v-action:query @click="queryTable()">查询</a-button>
              <a-button style="margin-left: 8px" @click="resetSearchQueryParamBtn()">重置</a-button>
              <a-button type="danger" style="margin-left: 8px" v-action:add @click="newContract()">新增</a-button>
            </span>
          </a-col>
        </a-row>
      </a-form>
    </div>
    <!-- :scroll="{ x: 1300 }" -->
    <s-table
      ref="table"
      size="default"
      rowKey="id"
      :columns="columns"
      :data="loadData"
      :alert="options.alert"
      :rowSelection="options.rowSelection"
      showPagination="auto"
    >
      <span slot="totalAmount" slot-scope="text, record">
        <a-tag :color="record.contractNature === '1' ? 'red' : 'green'" >{{ text }}</a-tag>
      </span>
      <span slot="partA" slot-scope="text, record">
        <span style="display: none">{{ text }}</span>
        <span v-show="record.contractNature === '1'">{{ record.partA }}</span>
        <span v-show="record.contractNature === '2'">{{ record.partB }}</span>
        <span v-show="record.contractNature === '3'">{{ record.partA }}</span>
      </span>
      <span slot="action" slot-scope="text, record">
        <template>
          <a v-action:get @click="showDetail(record)">详情</a>
          <a-divider v-show="showMoreBtn" type="vertical" />
          <a-dropdown v-show="showMoreBtn">
            <a class="ant-dropdown-link">
              更多 <a-icon type="down" />
            </a>
            <a-menu slot="overlay">
              <a-menu-item>
                <a href="javascript:;" v-action:edit @click="handleEdit(record)">编辑</a>
              </a-menu-item>
              <a-menu-item>
                <a href="javascript:;" v-action:upload @click="attachmentBtn(record)">附件</a>
              </a-menu-item>
              <a-menu-item>
                <a href="javascript:;" v-action:delete @click="delContract(record)">删除</a>
              </a-menu-item>
            </a-menu>
          </a-dropdown>
        </template>
      </span>
    </s-table>
    <a-modal
      :title="modal.title"
      style="top: 20px;"
      :width="800"
      v-model="modal.visible"
      :maskClosable="false"
    >
      <template slot="footer">
        <a-button v-show="modal.editType === 2 || modal.editType === 1" @click="showAttachmentBtn(modal.rowData)">附件</a-button>
        <a-button v-show="modal.editType !== 2" key="back" @click="handleCancel">
          取消
        </a-button>
        <a-button key="submit" type="primary" :loading="modal.loading" @click="handleOk">
          {{ modal.editType === 2 ? '返回' : '保存' }}
        </a-button>
      </template>
      <a-form class="permission-form" :form="form">
        <a-tabs default-active-key="1" style="margin-top: -24px">
          <a-tab-pane key="1" tab="基本信息">
            <a-form-item
              :labelCol="labelCol"
              :wrapperCol="wrapperCol"
              style="display: none"
            >
              <a-input
                v-decorator="['id']"
              />
            </a-form-item>
            <a-form-item
              :labelCol="labelCol"
              :wrapperCol="wrapperCol"
              label="合同名称"
            >
              <a-input
                :disabled="this.modal.editType === 2"
                placeholder="合同名称"
                v-decorator="[
                  'contractName',
                  {rules: [{ required: true, message: '请填写合同名称' },
                           {max: 100, message: '合同名称不能超过100字符'}]}]"
              />
            </a-form-item>
            <a-form-item
              :labelCol="labelCol"
              :wrapperCol="wrapperCol"
              label="部门"
            >
              <a-select
                :disabled="this.modal.editType === 2"
                v-decorator="[
                  'depId',
                  {rules: [{ required: true, message: '请填写部门' }]}]"
                placeholder="请选择部门">
                <!--<a-select-option v-for="dep in depList" :key="dep.codeDetail" :value="dep.codeDetail">{{ dep.codeContent1 }}</a-select-option>-->
                <a-select-option v-for="dep in depList" :key="dep.itemVal" :value="dep.itemVal">{{ dep.itemDesc }}</a-select-option>
              </a-select>
            </a-form-item>
            <a-form-item
              :labelCol="labelCol"
              :wrapperCol="wrapperCol"
              label="项目编号"
            >
              <a-input
                :disabled="this.modal.editType === 2"
                placeholder="项目编号"
                v-decorator="[
                  'proId',
                  {rules: [{max: 200, message: '项目编号不能超过200字符'}]}]"
              />
            </a-form-item>
            <a-form-item
              :labelCol="labelCol"
              :wrapperCol="wrapperCol"
              label="合同类別"
            >
              <a-select
                :disabled="this.modal.editType === 2"
                v-decorator="[
                  'contractType',
                  {rules: [{ required: true, message: '请填写合同类別' }]}]"
                placeholder="请选择合同类別">
                <a-select-option v-for="type in contractTypeList" :key="type.itemVal" :value="type.itemVal">{{ type.itemDesc }}</a-select-option>
              </a-select>
            </a-form-item>
            <a-form-item
              :labelCol="labelCol"
              :wrapperCol="wrapperCol"
              label="合同性质"
            >
              <a-select
                :disabled="this.modal.editType === 2"
                v-decorator="[
                  'contractNature',
                  {rules: [{ required: true, message: '请填写合同性质' }]}]"
                placeholder="请选择合同性质">
                <a-select-option v-for="nature in contractNatureList" :key="nature.itemVal" :value="nature.itemVal">{{ nature.itemDesc }}</a-select-option>
              </a-select>
            </a-form-item>
            <a-form-item
              :labelCol="labelCol"
              :wrapperCol="wrapperCol"
              label="总金额（元）"
            >
              <a-input
                :disabled="this.modal.editType === 2"
                placeholder="总金额"
                v-decorator="[
                  'totalAmount',
                  {rules: [{ required: true, message: '请输入总金额'},{ validator: amountValidator}]}]"
              />
            </a-form-item>
            <a-form-item
              :labelCol="labelCol"
              :wrapperCol="wrapperCol"
              label="甲方"
            >
              <a-input
                :disabled="this.modal.editType === 2"
                placeholder="甲方"
                v-decorator="[
                  'partA',
                  {rules: [{ required: true, message: '请输入甲方' },
                           {max: 100, message: '甲方不能超过100字符'}]}]"
              />
            </a-form-item>
            <a-form-item
              :labelCol="labelCol"
              :wrapperCol="wrapperCol"
              label="乙方"
            >
              <a-input
                :disabled="this.modal.editType === 2"
                placeholder="乙方"
                v-decorator="[
                  'partB',
                  {rules: [{ required: true, message: '请输入乙方' },
                           {max: 100, message: '乙方不能超过100字符'}]}]"
              />
            </a-form-item>
            <a-form-item
              :labelCol="labelCol"
              :wrapperCol="wrapperCol"
              label="其他签约方"
            >
              <a-input
                :disabled="this.modal.editType === 2"
                placeholder="其他签约方"
                v-decorator="[
                  'partC',
                  {rules: [{max: 100, message: '其他签约方不能超过100字符'}]}]"
              />
            </a-form-item>
            <a-form-item
              :labelCol="labelCol"
              :wrapperCol="wrapperCol"
              label="签约时间"
            >
              <a-date-picker
                :disabled="this.modal.editType === 2"
                v-decorator="[
                  'signTime',{
                    rules: [{ required: true, message: '请输入签约时间' }]
                  }]" />
            </a-form-item>
            <a-form-item
              :labelCol="labelCol"
              :wrapperCol="wrapperCol"
              label="签约地点"
            >
              <a-input
                :disabled="this.modal.editType === 2"
                placeholder="签约地点"
                v-decorator="[
                  'signAddr',
                  {rules: [{ required: true, message: '请输入签约地点' },
                           {max: 200, message: '签约地点不能超过200字符'}]}]"
              />
            </a-form-item>
            <a-form-item
              :labelCol="labelCol"
              :wrapperCol="wrapperCol"
              label="合同有效期"
            >
              <a-range-picker
                :disabled="this.modal.editType === 2"
                v-decorator="[
                  'rangeTime',
                  {rules: [{ type: 'array', required: true, message: '请输入合同有效期' }]}]" />
            </a-form-item>
            <a-form-item
              :labelCol="labelCol"
              :wrapperCol="wrapperCol"
              label="付款方式"
            >
              <a-textarea
                :disabled="this.modal.editType === 2"
                placeholder="付款方式"
                :rows="4"
                v-decorator="[
                  'payment',
                  {rules: [{ max: 500, required: true, message: '请输入付款方式' }]}]"
              />
            </a-form-item>
            <a-form-item
              :labelCol="labelCol"
              :wrapperCol="wrapperCol"
              label="备注"
            >
              <a-textarea
                :disabled="this.modal.editType === 2"
                v-decorator="[
                  'note',
                  {rules: [{max: 200, message: '备注不能超过200字符'}]}]"
                placeholder="备注"
                :rows="4" />
            </a-form-item>
          </a-tab-pane>
          <a-tab-pane key="2" tab="合同内容">
            <a-form-item>
              <a-textarea
                :disabled="this.modal.editType === 2"
                v-decorator="[
                  'contractContent',
                  {rules: [{max: 1000, message: '合同内容不能超过1000字符'}]}]"
                :rows="10" />
            </a-form-item>
          </a-tab-pane>
<!--          <a-tab-pane v-show="modal.editType === 2 || modal.editType === 1" key="3" tab="附件">-->
<!--            <a-list bordered :data-source="modal.fileList">-->
<!--              <a-list-item slot="renderItem" slot-scope="item, index">-->
<!--                {{ item.name }}-->
<!--              </a-list-item>-->
<!--              <div slot="header">-->
<!--                <a-button :disabled="modal.editType === 2 || modal.editType === 0" @click="showAttachmentBtn(modal.rowData)">上传附件</a-button>-->
<!--              </div>-->
<!--            </a-list>-->
<!--          </a-tab-pane>-->
        </a-tabs>
      </a-form>
    </a-modal>
    <AttachmentModal ref="attachmentModal" :uploadDisabled="modal.uploadDisabled" :attachmentType="'1'" />
  </a-card>
</template>

<script>
import { STable, Ellipsis } from '@/components'
import AttachmentModal from './modules/AttachmentModal'
import * as api from '../../api/dataManage'
import * as codeApi from '../../api/common'
import pick from 'lodash.pick'
import moment from 'moment'
import { mapGetters } from 'vuex'
import store from '@/store'

export default {
  name: 'Contract',
  components: {
    STable,
    Ellipsis,
    AttachmentModal
  },
  computed: {
    ...mapGetters(['depInfo', 'roles', 'conDepList'])
  },
  data () {
    return {
      modal: {
        title: '',
        visible: false,
        loading: false,
        editType: 0, // 0 新增状态， 1 编辑状态, 2 详情状态不可编辑
        rowData: {},
        uploadDisabled: false
      },
      labelCol: {
        xs: { span: 24 },
        sm: { span: 5 }
      },
      wrapperCol: {
        xs: { span: 24 },
        sm: { span: 16 }
      },
      form: this.$form.createForm(this),
      // 部门列表
      depList: [],
      // 是否显示部门名称查询框 在部门经理进来时隐藏此查询框
      showDepName: true,
      // 控制展示更多按钮
      showMoreBtn: true,
      // 合同类別
      contractTypeList: [],
      // 合同性质
      contractNatureList: [],
      mdl: {},
      // 高级搜索 展开/关闭
      advanced: false,
      // 查询参数
      queryParam: {},
      // 导入按钮的loading
      importLoading: false,
      // 表头
      columns: [
        {
          title: '序号',
          dataIndex: '',
          width: '50px',
          key: 'rowIndex',
          customRender: (t, r, index) => {
            return ((this.paginationInfo.pageNum - 1) * this.paginationInfo.pageSize + index + 1)
          }
        },
        {
          title: '部门',
          dataIndex: 'depId',
          // scopedSlots: { customRender: 'depId' },
          customRender: (text, row, index) => {
            const depName = this.depList.filter(item => item.itemVal === text)
              ? this.depList.filter(item => item.itemVal === text)[0].itemDesc : text
            return <span>{depName}</span>
          },
          width: 150
        },
        {
          title: '合同名称',
          dataIndex: 'contractName'
          // ellipsis: true
        },
        {
          title: '签约时间',
          dataIndex: 'signTime',
          width: 120
        }, {
          title: '签约方',
          dataIndex: 'partA',
          scopedSlots: { customRender: 'partA' }
          // ellipsis: true
        },
        {
          title: '总金额',
          dataIndex: 'totalAmount',
          scopedSlots: { customRender: 'totalAmount' },
          width: 100
        },
        {
          title: '操作',
          dataIndex: 'action',
          width: '150px',
          scopedSlots: { customRender: 'action' }
        }
      ],
      paginationInfo: null,
      // 加载数据方法 必须为 Promise 对象
      loadData: parameter => {
        this.paginationInfo = parameter
        return api.GetContractList(Object.assign(parameter, this.queryParam))
          .then(res => {
            if (res.code === 200) {
              console.log('ContractInfo', res.result)
              return res.result
            } else if (res.code === 500) {
              this.$message.error('查询失败，' + res.msg)
              return {
                list: []
              }
            }
          })
      },
      selectedRowKeys: [],
      selectedRows: [],

      // custom table alert & rowSelection
      options: {
        alert: { show: false, clear: () => { this.selectedRowKeys = [] } },
        rowSelection: {
          selectedRowKeys: this.selectedRowKeys,
          onChange: this.onSelectChange
        }
      },
      optionAlertShow: false
    }
  },
  filters: {
  },
  beforeCreate () {
    // codeApi.LasCodeItem({ itemTypeId: 101 }).then(res => {
    //   this.depList = res.result
    // })
    // 合同类別
    codeApi.LasCodeItem({ itemTypeId: 102 }).then(res => {
      this.contractTypeList = res.result
    })
    // 合同性质
    codeApi.LasCodeItem({ itemTypeId: 104 }).then(res => {
      this.contractNatureList = res.result
    })
  },
  created () {
    console.log(this.conDepList)
    this.depList = this.conDepList
    this.tableOption()
    const menuList = store.getters.menus
    const buttonArr = menuList.filter(item => item.menuUrl === this.$route.path)[0].actionList
    if (!buttonArr.includes('edit') && !buttonArr.includes('delete') && !buttonArr.includes('upload')) {
      this.showMoreBtn = false
    }
    // if (this.roles.name === '部门经理') {
    //   this.showDepName = false
    //   this.queryParam.depId = this.depInfo.contractDepId
    // }
  },
  mounted () {
  },
  methods: {
    newContract () {
      this.modal.title = '新增合同'
      this.form.resetFields()
      this.modal.loading = false
      this.modal.editType = 0
      this.modal.visible = true
      this.modal.rowData = {}
    },
    tableOption () {
      if (!this.optionAlertShow) {
        this.options = {
          alert: { show: false, clear: () => { this.selectedRowKeys = [] } },
          rowSelection: {
            selectedRowKeys: this.selectedRowKeys,
            onChange: this.onSelectChange
          }
        }
        this.optionAlertShow = true
      } else {
        this.options = {
          alert: false,
          rowSelection: null
        }
        this.optionAlertShow = false
      }
    },
    handleEdit (record) {
      this.modal.title = '修改合同'
      this.modal.loading = false
      this.modal.editType = 1
      this.modal.visible = true
      this.modal.rowData = record
      this.modal.uploadDisabled = false
      console.log('record', record)
      this.$nextTick(() => {
        this.form.setFieldsValue(pick(record, ['id', 'depId', 'contractName', 'proId', 'contractType', 'contractNature',
          'totalAmount', 'partA', 'partB', 'partC', 'signAddr', 'payment', 'note', 'contractContent']))
        this.form.setFieldsValue({
          'signTime': moment(record.signTime),
          'rangeTime': [moment(record.beginDate), moment(record.endDate)]
        })
      })
    },
    handleOk (e) {
      e.preventDefault()
      if (this.modal.editType === 2) {
        this.modal.visible = false
        return
      }
      this.modal.loading = true
      this.form.validateFields((err, values) => {
        if (err == null) {
          setTimeout(() => {
            values.signTime = values.signTime.format('YYYYMMDD')
            values.beginDate = values.rangeTime[0].format('YYYYMMDD')
            values.endDate = values.rangeTime[1].format('YYYYMMDD')
            delete values.rangeTime
            values.totalAmount = parseFloat(values.totalAmount)
            console.log('保存的数据', values)
            api.SaveContract(values).then(res => {
              console.log(res)
              if (res.code === 200) {
                if (res.msg.indexOf('成功') >= 0) {
                  this.$message.success('保存成功！')
                  this.$refs.table.refresh(true)
                  this.modal.loading = false
                  this.modal.visible = false
                } else {
                  this.$message.error('保存失败！' + res.msg)
                  this.modal.loading = false
                }
              } else {
                this.$message.error('服务出错' + res.msg)
                this.modal.loading = false
              }
            }).catch(e => {
              this.$message.error('保存失败！')
              this.modal.loading = false
              console.error(e)
            })
          }, 2000)
        } else {
          this.$message.error('存在非法输入！')
          setTimeout(() => {
            this.modal.loading = false
            this.$nextTick(() => { this.modal.loading = false })
          }, 500)
        }
      })
    },
    onSelectChange (selectedRowKeys, selectedRows) {
      this.selectedRowKeys = selectedRowKeys
      this.selectedRows = selectedRows
    },
    toggleAdvanced () {
      this.advanced = !this.advanced
    },
    amountValidator (rule, value, callback) {
      const reg = /((^[1-9]\d{0,16})|^0)(\.\d{0,3}){0,1}$/
      if (value && !reg.test(value)) {
        callback(new Error('整数部分不超过17位，小数位不超过3位'))
      } else {
        callback()
      }
    },
    delContract (record) {
      const _this = this
      this.$confirm({
        title: '确定删除该合同么',
        okText: '确认',
        okType: 'danger',
        cancelText: '取消',
        onOk () {
          api.DelContract({ id: record.id }).then(res => {
            if (res.code === 200) {
              if (res.msg.indexOf('成功') >= 0) {
                _this.$message.success('删除成功！')
                _this.$refs.table.refresh(true)
              } else {
                _this.$message.error('删除失败！' + res.msg)
              }
            } else {
              _this.$message.error('服务出错' + res.msg)
            }
          })
        },
        onCancel () {
        }
      })
    },
    excelExport () {
      const ids = this.selectedRows.map(item => {
        return item.id
      })
      console.log('ids', ids)
      if (ids.length === 0) {
        this.$message.warning('请勾选需要导出的数据')
        return
      }
      api.ExportContract({ ids: ids }).then((result) => {
        console.log(result)
        const _this = this
        const r = new FileReader()
        r.readAsText(result)
        r.onload = function () {
          try {
            const res = JSON.parse(this.result)
            console.log(res)
            if (res.code && res.code === 500) {
              _this.$message.error('导出失败，' + res.msg)
            }
          } catch (err) {
            const link = document.createElement('a')
            link.href = window.URL.createObjectURL(new Blob([result]))
            link.target = '_blank'
            link.download = '合同列表.xls'
            document.body.appendChild(link)
            link.click()
            document.body.removeChild(link)
          }
        }
      }).catch((err) => {
        console.log(err)
        this.$message.error('导出失败')
        this.$message.error(err)
      })
    },
    excelImport () {
      this.$refs.importInput.click()
    },
    importFile () {
      this.importLoading = true
      const file = document.querySelector('#importFile').files[0]
      if (file === null) {
        this.importLoading = false
        return
      }
      const fileName = file.name
      const fileSize = file.size / (1024 * 1024)
      const idx = fileName.lastIndexOf('.')
      if (idx !== -1) {
        let ext = fileName.substr(idx + 1).toUpperCase()
        ext = ext.toLowerCase()
        if (ext !== 'xls' && ext !== 'xlsx') {
          this.$message.error('导入文件格式不对, 只能导入xls,xlsx格式文件！')
          this.importLoading = false
          return
        }
      } else {
        this.$message.error('导入文件格式不对, 只能导入xls,xlsx格式文件！')
        this.importLoading = false
        return
      }
      if (fileSize > 10) {
        this.$message.error('导入文件大小不能超过10MB')
        this.importLoading = false
        return
      }
      const formData = new FormData()
      formData.append('file', file)
      console.log(file)
      this.$refs.importInput.value = null
      api.ImportContract(formData).then(res => {
        console.log(res)
        if (res.code === 200 && res.result === '导入成功') {
          this.$message.success('导入成功')
          this.importLoading = false
          this.$refs.table.refresh(true)
        } else {
          this.$message.error('导入失败！')
          this.$warning({
            title: '导入失败',
            content: (h) => {
              const data = res.msg
              return h('a-textarea', {
                attrs: {
                  readonly: true
                },
                props: {
                  defaultValue: data,
                  autoSize: { minRows: 5, maxRows: 10 }
                }
              })
            }
          })
          this.importLoading = false
        }
      }).catch(e => {
        console.error(e)
        this.$message.error('导入失败！')
        this.importLoading = false
      })
    },
    showDetail (record) {
      this.modal.title = '合同详情'
      this.modal.loading = false
      this.modal.editType = 2
      this.modal.visible = true
      this.modal.rowData = record
      this.modal.uploadDisabled = true
      console.log('record', record)
      this.$nextTick(() => {
        this.form.setFieldsValue(pick(record, ['id', 'depId', 'contractName', 'proId', 'contractType', 'contractNature',
          'totalAmount', 'partA', 'partB', 'partC', 'signAddr', 'payment', 'note', 'contractContent']))
        this.form.setFieldsValue({
          'signTime': moment(record.signTime),
          'rangeTime': [moment(record.beginDate), moment(record.endDate)]
        })
      })
    },
    queryTable () {
      delete this.queryParam.signTimeBegin
      delete this.queryParam.signTimeEnd
      delete this.queryParam.beginDate
      delete this.queryParam.endDate
      if (this.queryParam.signTimeTemp && this.queryParam.signTimeTemp.length !== 0) {
        this.queryParam.signTimeBegin = this.queryParam.signTimeTemp[0].format('YYYYMMDD')
        this.queryParam.signTimeEnd = this.queryParam.signTimeTemp[1].format('YYYYMMDD')
      }
      if (this.queryParam.rangeTime && this.queryParam.rangeTime.length !== 0) {
        this.queryParam.beginDate = this.queryParam.rangeTime[0].format('YYYYMMDD')
        this.queryParam.endDate = this.queryParam.rangeTime[1].format('YYYYMMDD')
      }
      this.$refs.table.refresh(true)
    },
    handleCancel () {
      this.modal.visible = false
    },
    resetSearchQueryParamBtn () {
      this.queryParam = {}
      this.queryTable()
    },
    attachmentBtn (record) {
      this.modal.uploadDisabled = false
      this.showAttachmentBtn(record)
    },
    showAttachmentBtn (record) {
      this.$refs.attachmentModal.clearFileList()
      this.$refs.attachmentModal.show(record)
    },
    getAttachment (id) {
      api.Attachment({
        attachmentType: '1',
        id: id
      }).then(res => {
        res.result.forEach(item => {
          const obj = {
            uid: item.id, // 文件唯一标识，建议设置为负数，防止和内部产生的 id 冲突
            name: item.attachmentName, // 文件名
            status: 'done', // 状态有：uploading done error removed
            // response: '{"status": "success"}', // 服务端响应内容
            linkProps: '{"download": "' + item.attachmentName + '"}', // 下载链接额外的 HTML 属性
            // xhr: 'XMLHttpRequest{ ... }' // XMLHttpRequest Header
            url: 'http://' + item.attachmentUrl.replace('172.19.99.162', '101.132.166.121')
          }
          this.modal.fileList.push(obj)
        })
      })
    }
  }
}
</script>
